import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const topCategory = () => import('@/views/category/TopCategory')
const SubCategory = () => import('@/views/category/SubCategory')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login/index')
const LoginCallback = () => import('@/views/login/Callback')
const Cart = () => import('@/views/cart')
const Checkout = () => import('@/views/pay/Checkout')

const routes = [
  // 1.一级路由
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home
      },
      {
        path: 'category/:id',
        component: topCategory,
        props: true
      },
      {
        path: 'category/sub/:id',
        component: SubCategory
      },
      {
        path: '/product/:id',
        component: Goods
      },
      {
        path: 'cart',
        component: Cart
      },
      {
        path: 'member/checkout',
        component: Checkout
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: LoginCallback
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    return {
      left: 0, top: 0
    }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 地址以member开头需要登录
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
